<template>
  <a-row :class="['p-4']" :gutter="10">
    <a-col :xl="6" :lg="8" :md="10" :sm="24" style="flex: 1">
      <a-card :bordered="false" style="height: 100%">
        <a-button
          type="primary"
          :icon="h(PlusOutlined)"
          @click="addType"
          style="margin-bottom: 20px"
          v-auth="'dict:add'"
          >新增</a-button
        >
        <a-tree
          :tree-data="treeData.list"
          @select="changeSelect"
          :fieldNames="treeFieldnames"
          v-model:selectedKeys="selectedKeys"
          :expandedKeys.sync="expandedKeys"
        >
          <template #title="{ key: treeKey, name, id }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ name }}</span>
              <template #overlay>
                <a-menu
                  @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey, id)"
                >
                  <a-menu-item key="1">编辑</a-menu-item>
                  <a-menu-item key="2">删除</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </a-card>
    </a-col>
    <a-col :xl="18" :lg="16" :md="14" :sm="24" style="flex: 1">
      <a-card :bordered="false" style="height: 100%">
        <BasicTable @register="registerTable">
          <template #headerTop>
            <a-alert v-if="nowSelectName" :message="nowSelectName" type="info" />
          </template>
          <template #action="{ record }">
            <TableAction :actions="getTableAction(record)" />
          </template>
        </BasicTable>
      </a-card>
    </a-col>
  </a-row>
  <a-drawer
    v-model:visible="editTypeModel"
    :title="typeData.type == 'add' ? '新增类型' : '编辑类型'"
    width="520"
    :footer-style="{ textAlign: 'right' }"
    @close="resetType"
  >
    <a-form :model="typeData.data" v-bind="layout" name="nest-messages">
      <a-form-item label="父节点">
        <a-tree-select
          :fieldNames="fieldNames"
          v-model:value="typeData.data.parentId"
          show-search
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择父节点"
          allow-clear
          :tree-data="treeDataSelect.list"
          tree-node-filter-prop="label"
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item :name="['name']" label="类型名称">
        <a-input v-model:value="typeData.data.name" />
      </a-form-item>
      <a-form-item :name="['code']" label="类型编号">
        <a-input v-model:value="typeData.data.code" />
      </a-form-item>
      <a-form-item :name="['inputCode']" label="输入码">
        <a-input v-model:value="typeData.data.inputCode" />
      </a-form-item>
      <a-form-item :name="['iconUrl']" label="图标">
        <RwUpload
          :value="typeData.data.iconUrl"
          :base_url="base_url"
          :uploadUrl="uploadUrl"
          @changeValuie="changeEmit"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button style="margin-right: 8px" @click="resetType">取消</a-button>
      <a-button type="primary" @click="saveType">确认</a-button>
    </template>
  </a-drawer>
</template>
<script lang="ts" setup>
import { BasicTable, TableAction } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { PlusOutlined } from "@ant-design/icons-vue";
import { uploadUrl } from "/@/api/common/api";
import { columns, searchFormSchema } from "./dict.data";
import { list, listTypeApi, Type, allList, delInfo } from "./dict.api";
import { ITreeData, IResultTreeData, IFormatTreeData } from "./dict.type";
import { ref, reactive, onBeforeMount, h } from "vue";
import { SystemStore, ITemplate } from "/@/store/modules/system";
import RwUpload from "/@/components/RW/upload.vue";
import { useMessage } from "/@/hooks/web/useMessage";
const system = SystemStore();
const checkedKeys = ref<Array<string | number>>([]);
const dicttemplateModel = ref<boolean>(false);
const dictaddModel = ref<boolean>(false);
const editTypeModel = ref<boolean>(false);
const selectedKeys = ref<string>("");
const { createMessage: msg } = useMessage();
const windowInstanse = window;
let formFaildList = reactive<ITemplate[]>([]);
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};
let formData = reactive({});
const typeData = reactive({
  type: "add",
  data: {},
});
const base_url = ref<string>("");
base_url.value = windowInstanse.config.base_url;
const onFinish = (values: any) => {
  console.log(values, "values");
};
const getList = () => {
  if (!selectId.value) return;
  listTypeApi(selectId.value).then((res) => {
    try {
      setTableData(res.data.entities);
    } catch {}
  });
};
const { prefixCls, tableContext } = useListPage({
  tableProps: {
    title: "",
    api: getList,
    columns: columns,
    size: "small",
    pagination: true,
    isTreeTable: true,
    expandIconColumnIndex: 1,
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    showHeader: true,
    tableSetting: { fullScreen: true },
    formConfig: {
      // schemas: searchFormSchema,
      showResetButton: false,
      showSubmitButton: false,
    },
    actionColumn: {
      width: 70,
    },
  },
});
const treeFieldnames = {
  children: "children",
  title: "name",
  key: "id",
};
const fieldNames = {
  // tree-select
  children: "children",
  label: "name",
  value: "id",
};
const [
  registerTable,
  { reload, expandAll, collapseAll, setColumns, setTableData },
] = tableContext;
const selectId = ref<string>("");
const nowSelectName = ref<string>("");
const onSelectChange = <T>(e: T) => {};
const rowSelection = {
  type: "checkbox",
  columnWidth: 30,
  selectedRowKeys: checkedKeys,
  onChange: onSelectChange,
};

const typeId = ref<string | number>("");
const onContextMenuClick = (treeKey: string, menuKey: string, id) => {
  /** 右键菜单点击事件 */
  typeId.value = treeKey;
  system.setTemplateId(typeId.value);

  switch (menuKey) {
    case "1":
      // 类型编辑
      editTypeModel.value = true;
      typeData.type = "edit";
      typeData.data = SelectData;
      break;
    case "2":
      // 删除类型
      console.log(id, "treeKey");
      dictaddModel.value = true;
      handleDelete({ id });
      break;
  }
};

const pushContent = () => {
  if (!selectId.value) return msg.error("请选择要新增的字典类型");
  formData = {};
  dictaddModel.value = true;
};

// 获取树列表

let treeData = reactive({ list: [] });
let SelectData = reactive<ITreeData>(([] as unknown) as ITreeData);
let treeDataSelect = reactive({ list: [] });
const getTreeData = (): void => {
  list(0).then((res: IResultTreeData) => {
    try {
      treeData.list = res.data;
    } catch {}
  });
};
const getTreeDataAll = (): void => {
  allList(0).then((res: IResultTreeData) => {
    try {
      treeDataSelect.list = res.data;
      treeDataSelect.list.unshift({ name: "父节点", id: "0", value: "0", parentId: "0" });
    } catch {}
  });
};
const getTree = (): void => {
  getTreeData();
  getTreeDataAll();
};
// 监听树列表点击
const changeSelect = (selectedKeys, e) => {
  // typeInfo(e.node.code).then((res: any) => {
  nowSelectName.value = e.node.name;
  selectId.value = selectedKeys[0];
  SelectData = e.node.dataRef;
  // });
  getList();
};

getTree();

const saveType = (): void => {
  // 保存类型
  Type[typeData.type](typeData.data).then((res: IResultTreeData) => {
    if (res.isSucceed) {
      msg.success(res.msg || "保存成功");
    } else {
      msg.error(res.msg || "保存失败");
    }
    resetType();
    getTree();
  });
};
const changeEmit = (e): void => {
  typeData.data.iconUrl = e;
};
const addType = (): void => {
  editTypeModel.value = true;
  typeData.type = "add";
  typeData.data = {};
  typeData.data.parentId = selectId.value;
};
const resetType = (): void => {
  editTypeModel.value = false;
  typeData.type = "add";
  typeData.data = {};
  getList();
};
function handleEdit(record) {
  console.log(record, "record");
  editTypeModel.value = true;
  typeData.type = "edit";
  typeData.data = record;
}
function handleDelete(record) {
  if (record) {
    delInfo(record.id).then((res) => {
      if (res.isSucceed) {
        msg.success(res.msg || "删除成功");
      } else {
        msg.error(res.msg || "删除失败");
      }
      resetType();
      getTree();
    });
  }
}
function getTableAction(record) {
  return [
    {
      label: "编辑",
      onClick: handleEdit.bind(null, record),
      auth: "dict:edit",
    },
    {
      label: "删除",
      auth: "dict:delete",
      popConfirm: {
        title: "是否确认删除",
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

/**  处理添加模板成功逻辑 */
</script>

<style lang="less" scoped>
.editFormBody {
  margin: 10px;
}
</style>
